package net.neptech.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import net.neptech.model.dto.FileVO;
import net.neptech.service.FileService;
import net.neptech.vm.ResponseResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @Author Saya
 * @Date 2025/8/24 22:56
 * @Description TODO
 **/
@RestController
@RequestMapping(value = {"file"})
@RequiredArgsConstructor
public class FileController {
    private final FileService fileService;
    @Value("${file.dir}")
    private String fileDir;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @PostMapping("upload")
    public ResponseResult<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        return ResponseResult.success(fileService.save(file.getBytes(), originalFilename));

    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @PostMapping("uploadBase64")
    public ResponseResult<String> uploadBase64(@RequestBody FileVO file) {
        File f = new File(StrUtil.format("/tmp/{}_{}", IdUtil.fastSimpleUUID(), file.getFileName()));
        try {
            Base64.decodeToFile(file.getBase64(), f);
            return ResponseResult.success(fileService.save(FileUtil.readBytes(f), file.getFileName()));
        } finally {
            FileUtil.del(f);
        }
    }

    /**
     * 显示文件
     */
    @SneakyThrows
    @GetMapping("/show/{key}")
    public void show(@PathVariable String key, HttpServletResponse response) {
        String format = StrUtil.format("{}/{}", fileDir, key);
        IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(format));
    }

    /**
     * 显示文件
     *
     * @param key
     */
    @SneakyThrows
    @GetMapping("/show/{s}/{key}")
    public void show(@PathVariable String key, @PathVariable String s, HttpServletResponse response) {
        String format = StrUtil.format("{}/{}/{}", fileDir, s, key);
        IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(format));
    }
}
